package org.opens.controller;

import com.alibaba.fastjson.JSON;
import com.github.benmanes.caffeine.cache.Cache;
import org.opens.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Map;

/**
 * 功能:
 *
 * @author zym
 * @Date 2022/6/29 14:26
 */
@RestController
@RequestMapping(value = "/api/caffeine")
public class CaffeineController {

    @Autowired(required = false)
    private Cache<String, Object> caffeineCache;

    @Autowired(required = false)
    private CacheManager caffeineCacheManager;

    @RequestMapping(value = "/cache/all")
    public R<Map<String, Object>> getAll() {
        return R.success(caffeineCache.asMap());
    }

    @RequestMapping(value = "/cacheNames")
    public R<Collection<String>> getAll2() {
        Collection<String> cacheNames = caffeineCacheManager.getCacheNames();
        return R.success(cacheNames);
    }

    @RequestMapping(value = "/cache")
    public R<String> getCache(@RequestParam(value = "name") String name, @RequestParam(value = "id") String id) {
        org.springframework.cache.Cache cache = caffeineCacheManager.getCache(name);
        org.springframework.cache.Cache.ValueWrapper valueWrapper = cache.get("RedisCacheEntity_" + id);
        return R.success(JSON.toJSONString(valueWrapper.get()));
    }

}
